var express = require('express');
var querydb = require('../utils/querydb');
var router = express.Router(); //获取路由对象



// ======================================
// ============banner管理================
// ======================================
router.get('/banner', (req,res,next) => {
    const sql = 'SELECT id,url,content,number FROM y_banner ORDER BY number DESC'; 
    querydb(sql).then(data=>{
        if(data != null && data.length > 0){
            res.send({
                resultCode: 1,
                resultInfo: {
                    list: data
                },
            })
        }else{
            res.send({
                resultCode: -1,
                resultInfo: '没有数据',
            });
        }
    })
})

/* 
 * 添加banner
 */
router.post("/banner/add", (req, res) => {
    const url = req.body.url; //接收表单参数
    const content = req.body.content; // 内容
    const number = req.body.number;  //显示序号，值越大越排前

    const sql = 'INSERT INTO y_banner (url,content,number) VALUES (?,?,?)'
    const params = [url,content,number];

    querydb(sql, params).then(data => {
        console.log("添加banner数据成功!");
        res.send({
            resultCode: 1,
            resultInfo: 'ok',
        });
    }).catch(error => {
        res.send({
            resultCode: -1,
            resultInfo: 'no',
        });
    });

})


/* 删除Banner */
router.get('/banner/delete', (req, res, next) => {
    const id = req.query.id;
    const sql = "DELETE FROM y_banner WHERE id = ?";
    const params = [id];
    querydb(sql, params).then(data => {
        res.send({
            resultCode: 1,
            resultInfo: 'ok'
        })
    })
})
// ==================================
// =======商品模块====================
// ==================================

/* 商品列表 */
router.get('/list', (req, res) => {
    var pageSize = 10; // 每页记录条数
    var totalNo = 0; // 总记录条数
    var pagesNum = 0; // 总页数
    if (req.query.pageSize) {
        pageSize = req.query.pageSize;
        pageSize = parseInt(pageSize);
    }
    // ===接收参数页号====
    var currentNo = req.query.pageNo; // 当前页号
    if (currentNo == null && typeof (currentNo) === 'undefined') {
        currentNo = 1;
    }
    // console.log('currentNo :' + currentNo, ' pageSize :', pageSize);
    // ==== 总页数

    querydb('SELECT count(*) as num FROM y_product').then(data => {
        totalNo = data[0].num; // 总记录条数
        if (totalNo % pageSize === 0) {
            pagesNum = totalNo / pageSize;
        } else {
            pagesNum = totalNo / pageSize + 1;
        }
        // console.log('总页数 ' + parseInt(pagesNum));

        // ==== 根据偏移量查询分页记录
        var start = (currentNo - 1) * pageSize; // 偏移量

        var sql = "SELECT y_product.id,shop,picture,product,price,oldprice,putaway,detail, y_category.name as categoryname FROM y_product,y_category WHERE y_product.category_id = y_category.id ORDER BY id DESC  LIMIT ?, ? ";
        var param = [start, pageSize];
        return querydb(sql, param);
    }).then(dataTwo => {
        // console.log(JSON.stringify(dataTwo));
        if (dataTwo != null && dataTwo.length > 0) {
            res.send({
                resultCode: 1,
                resultInfo: {
                    total: totalNo,
                    currentNo: parseInt(currentNo),
                    pageSize: parseInt(pageSize),
                    totalNum: parseInt(pagesNum),
                    list: dataTwo
                },
            })
        } else {
            res.send({
                resultCode: -1,
                resultInfo: '没有数据',
            });
        }
    })
})


/* 
 * 添加商品
 */
router.post("/add", (req, res) => {
    const shop = req.body.shop; //接收表单参数
    const picture = req.body.picture;
    const product = req.body.product;
    const price = req.body.price;
    const oldprice = req.body.oldprice;
    const putaway = req.body.putaway;
    const detail = req.body.detail;
    const categoryId = req.body.categoryId

    console.log('categoryId ',categoryId, " shop :",shop);

    const sql = 'INSERT INTO y_product (shop,picture,product,price,oldprice,putaway,detail,category_id) VALUES (?,?,?,?,?,?,?,?)'
    const params = [shop,picture,product,price,oldprice,putaway,detail,categoryId];

    querydb(sql, params).then(data => {
        console.log("添加商品数据成功!");
        res.send({
            resultCode: 1,
            resultInfo: 'ok',
        });
    }).catch(error => {
        console.log('error ',error);
        res.send({
            resultCode: -1,
            resultInfo: 'no',
        });
    });

})


/* 删除商品 */
router.get('/delete', (req, res, next) => {
    const id = req.query.id;
    const sql = "DELETE FROM y_product WHERE id = ?";
    const params = [id];
    querydb(sql, params).then(data => {
        res.send({
            resultCode: 1,
            resultInfo: 'ok'
        })
    })
})


/**
 * 查询商品
 * parms: id
 */
router.get("/find", function (req, res, next) {
    var id = req.query.id; //接收表单参数
    if (!id) {
        res.send({
            resultCode: -1,
            resultInfo: '参数出错',
        })
        return
    }

    var sql = "SELECT id,shop,picture,product,price,oldprice,putaway,detail,category_id FROM y_product WHERE id = ?";
    var parameters = [id];

    querydb(sql, parameters).then(function (data) {
        res.send({
            resultCode: 1,
            resultInfo: data[0],
        });
    }).catch(next);

});

// ===============================================================
// ======================菜品分类=============================
// ===============================================================

/**
 * 所有分类
 */
router.get('/category/list', (req,res,next) => {
    const sql = 'SELECT id,name FROM y_category'; 
    querydb(sql).then(data=>{
        if(data != null && data.length > 0){
            res.send({
                resultCode: 1,
                resultInfo: {
                    list: data
                },
            })
        }else{
            res.send({
                resultCode: -1,
                resultInfo: '没有数据',
            });
        }
    })
})


/* 
 * 添加商品分类
 */
router.post("/category/add", (req, res) => {
    const name = req.body.name; //接收表单参数
    // const desc = req.body.desc; // 字段desc关键字不能用，作费
    const sql = 'INSERT INTO y_category (name) VALUES (?)'
    const params = [name];

    querydb(sql, params).then(data => {
        console.log("添加商品分类数据成功!");
        res.send({
            resultCode: 1,
            resultInfo: 'ok',
        });
    }).catch(error => {
        console.log('error ',error);
        res.send({
            resultCode: -1,
            resultInfo: 'no',
        });
    });

})


/* 删除商品分类 */
router.get('/category/delete', (req, res, next) => {
    const id = req.query.id;
    const sql = "DELETE FROM y_category WHERE id = ?";
    const params = [id];
    querydb(sql, params).then(data => {
        res.send({
            resultCode: 1,
            resultInfo: 'ok'
        })
    })
})

module.exports = router;